<?php
class MemberController extends Zend_Controller_Action
{
	public function init()
	{
		$auth = Zend_Auth::getInstance ();
		if ($auth->hasIdentity ()) {
			$this->view->identity = $auth->getIdentity ();
		}

		// Set lang to view
		$this->view->lang = $this->_request->getParam ( 'lang', 'en' );
		$this->view->action = $this->getRequest()->getActionName();
	}

	public function addProductAction()
	{
		$productID = $this->_request->getParam ( 'product_id' );
		$quantity = $this->_request->getParam ( 'quantity' );
		
		$productNamespace = new Zend_Session_Namespace('products');
		if (isset($productNamespace->products)) {
			$productNamespace->products[$productID] = $quantity;
		} else {
			$productNamespace->products = array($productID => $quantity);
		}
		
		return $this->_redirect ( 'member/shoppingcart' );
	}
	
	public function removeProductAction()
	{
		$productID = $this->_request->getParam ( 'product_id' );
		
		$productNamespace = new Zend_Session_Namespace('products');
		if (isset($productNamespace->products)) {
			if(isset($productNamespace->products[$productID]))
			{
				unset($productNamespace->products[$productID]);
			}
		} 
		
		return $this->_redirect ( 'member/shoppingcart' );
	}

	public function shoppingcartAction() {
		$productNamespace = new Zend_Session_Namespace('products');
		if (isset($productNamespace->products)) {
			$products = $productNamespace->products;
		} else {
			$products = array();
		}
		
		if(count($products) == 0) {
			$this->render ( "shoppingcart-empty" );
		}
		
		
		$price = 0;
		$mdlProduct = new Model_Product();
		foreach($products as $productID => $quantity) 
		{
			$products[$productID] = array('quantity' => $products[$productID]);
			$products[$productID]['detail'] = $mdlProduct->findProduct($productID);
			
			$price += $products[$productID]['quantity'] * $products[$productID]['detail']['price'];
		}
		
		$this->view->price = $price;
		$this->view->products = $products;
		
		if($this->_request->getParam ( 'confirm' ) == 1) {
			$mdlOrder = new Model_Order();
			$orderID = $mdlOrder->createOrder($this->view->identity->id);
			
			$mdlOrderDetail = new Model_OrderDetail();
			foreach($products as $productID => $detail)
			{
				$mdlOrderDetail->createOrderDetail($orderID, $productID, $detail['detail']['price'], $detail['quantity']);
			}
			
			//reset session
			unset($productNamespace->products);
						
			$auth = Zend_Auth::getInstance ();
			$identity = $auth->getIdentity ();
			
			// send mail to user
			$mail = new CMS_Mail();
			$mail->setTemplate('shopping');
			$mail->title = "Hóa đơn";
			$mail->products = $products;
			$mail->price = $price;
			
			$mail->setRecipient($identity->email);
			$mail->send();
			
			$this->render ( "shoppingcart-confirm" );
		}
	}
}